{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "cc0bdac3",
   "metadata": {},
   "source": [
    "# API week4\n",
    "## 1.百度 Access token"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "id": "b5e5cde3",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "24.af6ed544851b7ea1a81f6418cb2c88dc.2592000.1681649878.282335-31381499\n"
     ]
    }
   ],
   "source": [
    "import requests\n",
    "import json\n",
    "\n",
    "\n",
    "def main():\n",
    "        \n",
    "    url = \"https://aip.baidubce.com/oauth/2.0/token?client_id=eP0d10jF2Z5vrMjmuQuLT8K5&client_secret=PZ0peGG9rCr8PQBGboIOACXNC6xdNpW7&grant_type=client_credentials\"\n",
    "    \n",
    "    payload = \"\"\n",
    "    headers = {\n",
    "        'Content-Type': 'application/json',\n",
    "        'Accept': 'application/json'\n",
    "    }\n",
    "    \n",
    "    response = requests.request(\"POST\", url, headers=headers, data=payload)\n",
    "    \n",
    "    print(response.json()[\"access_token\"])\n",
    "    \n",
    "\n",
    "if __name__ == '__main__':\n",
    "    main()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f2cfa03c",
   "metadata": {},
   "source": [
    "## 通用图像识别"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "id": "c0b1e184",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'error_code': 18, 'error_msg': 'Open api qps request limit reached'}\n"
     ]
    }
   ],
   "source": [
    "# encoding:utf-8\n",
    "\n",
    "import requests\n",
    "import base64\n",
    "\n",
    "'''\n",
    "通用物体和场景识别\n",
    "'''\n",
    "\n",
    "request_url = \"https://aip.baidubce.com/rest/2.0/image-classify/v2/advanced_general\"\n",
    "# 二进制方式打开图片文件\n",
    "f = open('/Users/henjunhao/Desktop/zh.jpeg', 'rb')\n",
    "img = base64.b64encode(f.read())\n",
    "\n",
    "params = {\"image\":img,\"baike_num\":1}\n",
    "access_token = '24.af6ed544851b7ea1a81f6418cb2c88dc.2592000.1681649878.282335-31381499'\n",
    "request_url = request_url + \"?access_token=\" + access_token\n",
    "headers = {'content-type': 'application/x-www-form-urlencoded'}\n",
    "response = requests.post(request_url, data=params, headers=headers)\n",
    "if response:\n",
    "    print (response.json())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "39bc2326",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.9.12"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
